import * as Mqtt from 'async-mqtt';

// 会话消息回调
export type TopicCallback = (data: string) => void;

/**
 * cloud 单一会话
 *
 * @author chitanda
 * @date 2022-11-28 17:11:12
 * @export
 * @class CloudTopic
 */
export class CloudTopic {
  /**
   * 所有当前 topic 订阅
   *
   * @author chitanda
   * @date 2022-11-28 18:11:10
   * @protected
   * @type {TopicCallback[]}
   */
  protected subs: TopicCallback[] = [];

  /**
   * Creates an instance of CloudTopic.
   *
   * @author chitanda
   * @date 2022-11-28 17:11:37
   * @param {CloudWSService} ws
   * @param {string} topic
   */
  constructor(
    protected client: Mqtt.AsyncMqttClient,
    protected topic: string,
  ) {}

  /**
   * 发送消息
   *
   * @author chitanda
   * @date 2022-11-29 14:11:43
   * @param {string} message
   * @return {*}  {Promise<void>}
   */
  publish(message: string): Promise<void> {
    return this.client.publish(this.topic, message);
  }

  /**
   * 收到 topic 消息，向本地所有回调发送
   *
   * @author chitanda
   * @date 2022-11-28 18:11:55
   * @param {string} message
   */
  send(message: string): void {
    this.subs.forEach(call => call(message));
  }

  /**
   * 订阅消息
   *
   * @author chitanda
   * @date 2022-11-28 18:11:23
   * @param {TopicCallback} callback
   */
  on(callback: TopicCallback): void {
    this.subs.push(callback);
  }

  /**
   * 取消消息订阅
   *
   * @author chitanda
   * @date 2022-11-28 18:11:30
   * @param {TopicCallback} callback
   */
  off(callback: TopicCallback): void {
    const i = this.subs.findIndex(c => c === callback);
    delete this.subs[i];
  }

  /**
   * 销毁
   *
   * @author chitanda
   * @date 2022-11-28 18:11:26
   * @return {*}  {Promise<void>}
   */
  async destroyed(): Promise<void> {
    this.subs = [];
  }
}
